import React, {useState, useEffect, useRef} from 'react'

import {BackTop, Space, Avatar, Input, Button, Dropdown, Menu, Tooltip, Drawer, Form, Radio, Upload, message, notification, Modal } from 'antd'
import {createFromIconfontCN, VerticalAlignTopOutlined, MessageOutlined, PlusOutlined, CloseCircleFilled, ExclamationCircleOutlined} from '@ant-design/icons'

import {Container, Header, Content, Footer, ThemeContainer, CallBackContainer} from './style'

import defaultSettings from '../../defaultSettings'

import LazyRouter from '../../components/LazyRouter'

import {Route, Redirect, Switch} from 'react-router-dom'

import {connect} from 'react-redux'

import {changeUserInfo, changeKeyword, changeHomeTopDis} from '../../store/actionCreators'

import {ThemeProvider} from 'styled-components'
import theme from './theme'
import store from 'store'

import MyRequest from '../../request/my_request'
import FeedbackRequest from '../../request/feedback_request'
import LoginRequest from '../../request/login_request'

const Home = LazyRouter(() => import('./home'))
const File = LazyRouter(() => import('./file'))
const Detail = LazyRouter(() => import('./detail'))
const Link = LazyRouter(() => import('./link'))

const IconFont = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/font_1745217_yxx4fbp62p.js',
})

const my_request = new MyRequest()
const feedback_request = new FeedbackRequest()
const login_request = new LoginRequest()

const { Search } = Input
const { confirm } = Modal

function Article(props){
    const {history, location, userInfo, detailTopDis, detailObj, changeUserInfo, changeKeyword, changeHomeTopDis} = props

    const [themeType, setThemeType] = useState('light')

    const [visibleDrawer, setVisibleDrawer] = useState(false)
    const [feedbackImg, setFeedbackImg] = useState('')
    const [feedbackLoading, setFeedbackLoading] = useState(false)

    const [form] = Form.useForm()
    const layout = {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
    }
    const tailLayout = {
        wrapperCol: { offset: 4, span: 20 },
    }

    const articleEl = useRef(null)
    const style = {
        height: 40,
        width: 40,
        lineHeight: '40px',
        borderRadius: 4,
        backgroundColor: '#1088e9',
        color: '#fff',
        textAlign: 'center',
        fontSize: 18,
    }
    const goMyWorkSpace = () => {
        if(userInfo.authority !== 'super'){
            return message.warning('暂未开放，敬请期待')
        }
        history.push('/main/workplace')
    }
    const goLogin = () => {
        history.push('/login')
    }
    //存储用户信息
    const saveUserInfo = () => {
        my_request.getUserInfo().then(res => {
            changeUserInfo(res.userinfo)
        })
    }

    //图片上传之前
    const beforeUpload = (file) => {
        let reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = (e) => {
            if(e.total > 3 * 1024 * 1024) return message.warning('图片不能超过3M！')
            setFeedbackImg(e.target.result)
        }
        return false
    }
    const deleteFBImg = (e) => {
        e.stopPropagation()
        setFeedbackImg('')
    }
    const addFeedback = (values) => {
        setFeedbackLoading(true)
        feedback_request.addFeedback({
            fbType: values.type,
            content: values.content,
            image: feedbackImg
        }).then(res => {
            form.setFieldsValue({
                type: '1',
                content: ''
            })
            setFeedbackImg('')
            setFeedbackLoading(false)
            setVisibleDrawer(false)
            notification.success({
                message: '反馈成功',
                description: '已收到您的留言反馈，感谢您为本站建设做出的努力！'
            })
        })
    }

    const startSearch = (value) => {
        changeKeyword(value)
    }

    const changeTheme = ({key}) => {
        setThemeType(key)
        store.set('theme', key)
    }

    const clickAvatar = () => {
        confirm({
            title: '是否退出当前账户?',
            icon: <ExclamationCircleOutlined />,
            content: '退出登录将无法点赞收藏',
            okText: '确认退出',
            onOk() {
                return new Promise((resolve, reject) => {
                    login_request.logout().then(res => {
                        changeUserInfo({})
                        resolve()
                    }).catch(() => {
                        reject()
                    })
                })
            },
            onCancel() {
                
            },
        })
    }

    useEffect(() => {
        saveUserInfo()
        setThemeType(store.get('theme') || 'light')
    }, [])
    return (
        <ThemeProvider theme={theme[themeType]}>
            <Container ref={articleEl} id="article-top-c">
                <Header>
                    <div className="nav-c">
                        <div className={'nav-avatar ' + (detailTopDis < 200 ? 'show' : 'hide')} onClick={() => history.push('/article/home')}>
                            <Avatar shape="square" src={defaultSettings.webUrl}></Avatar>
                            <div className="nav-avatar-name">八翼小站</div>
                        </div>
                        <div className={'nav ' + (detailTopDis < 200 ? 'show' : 'hide')}>
                            <span className={history.location.pathname === '/article/home' ? 'active' : ''} onClick={() => history.push('/article/home')}>首页</span>
                            <div className="line"></div>
                            <span className={history.location.pathname === '/article/file' ? 'active' : ''} onClick={() => history.push('/article/file')}>归档</span>
                            <div className="line"></div>
                            <span className={history.location.pathname === '/article/link' ? 'active' : ''} onClick={() => history.push('/article/link')}>友情链接</span>
                        </div>
                        <div className={'header-center ' + (detailTopDis < 200 ? 'show' : 'hide')}>
                            <Search style={{width: 300, margin: '0 32px'}} disabled={location.pathname !== '/article/home'} placeholder="请输入文章关键字" allowClear onSearch={startSearch} loading={false} enterButton />
                            <Button type="dashed" onClick={goMyWorkSpace} ghost={themeType === "dark"}>进入工作台</Button>
                        </div>
                        <div className={'title-name ' + (detailTopDis >= 200 ? 'show' : 'hide')}>{detailObj.title || ''}</div>
                        {
                            userInfo.username ? 
                            <Tooltip placement="bottom" title={'退出登录'}>
                                <Space className="user-state" onClick={clickAvatar}>
                                    <Avatar src={userInfo.avatar || defaultSettings.defaultAvatar}></Avatar>
                                    <span className="username">{userInfo.username}</span>
                                </Space>
                            </Tooltip> :
                            <Space className="user-state" onClick={goLogin}>
                                <span className="login">登录 / 注册</span>
                            </Space>
                        }
                    </div>
                </Header>
                <Content>
                    <Switch>
                        <Route path="/article" exact render={() => <Redirect to="/article/home"></Redirect>}></Route>
                        <Route path="/article/home" component={Home}></Route>
                        <Route path="/article/detail/:id" component={Detail}></Route>
                        <Route path="/article/file" component={File}></Route>
                        <Route path="/article/link" component={Link}></Route>
                    </Switch>
                </Content>
                <Footer style={{ textAlign: 'center' }}>
                    <div>{defaultSettings.title} ©2020 Created by {defaultSettings.author}</div>
                    <div className="beian">
                        <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=43010302001140">
                            <img src={require("../../assets/img/ga.png")}/>
                            湘公网安备 43010302001140号
                        </a>
                        <a target="_blank" href="http://beian.miit.gov.cn">湘ICP备20013444号-1</a>
                    </div>
                </Footer>
                <BackTop target={() => articleEl.current}>
                    <div style={style}><VerticalAlignTopOutlined /></div>
                </BackTop>
                <Dropdown placement="bottomCenter" trigger={['click']} overlay={
                    (
                        <Menu onClick={changeTheme} selectedKeys={[themeType]} >
                            <Menu.Item key="light">
                                <div>默认主题</div>
                            </Menu.Item>
                            <Menu.Item key="dark">
                                <div>暗夜主题</div>
                            </Menu.Item>
                        </Menu>
                    )
                }>
                    <ThemeContainer>
                        <IconFont type="icon-color" style={{fontSize: 24}}/>
                    </ThemeContainer>
                </Dropdown>
                <Tooltip placement="top" title="留言反馈">
                    <CallBackContainer onClick={() => setVisibleDrawer(true)}>
                        <MessageOutlined style={{fontSize: 18}}/>
                    </CallBackContainer>
                </Tooltip>
            </Container>
            {/* 反馈抽屉弹框 */}
            <Drawer
                title="留言反馈"
                placement="right"
                maskClosable={false}
                width={520}
                onClose={() => setVisibleDrawer(false)}
                visible={visibleDrawer}
            >
                <Form
                    form={form}
                    {...layout}
                    initialValues={{
                        type: '1'
                    }}
                    onFinish={addFeedback}
                >
                    <Form.Item
                        label="反馈类型"
                        name="type"
                        rules={[{ required: true }]}
                    >
                        <Radio.Group buttonStyle="solid">
                            <Radio.Button value="1">小站建议</Radio.Button>
                            <Radio.Button value="2">BUG反馈</Radio.Button>
                            <Radio.Button value="3">特殊需求</Radio.Button>
                            <Radio.Button value="4">其他</Radio.Button>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        label="反馈内容"
                        name="content"
                        rules={[{ required: true, message: '请填写反馈内容!' }]}
                    >
                        <Input.TextArea style={{width: '100%'}} placeholder="请填写反馈内容" rows={8}/>
                    </Form.Item>
                    <Form.Item
                        label="相关附图"
                    >
                        <Upload accept="image/*" beforeUpload={beforeUpload} showUploadList={false}>
                            <div className="upload-image-box">
                                {
                                    feedbackImg === '' ? 
                                    <React.Fragment>
                                        <PlusOutlined />
                                        <div>上传</div>
                                    </React.Fragment>
                                    :
                                    <React.Fragment>
                                        <img src={feedbackImg} alt=""/>
                                        <CloseCircleFilled onClick={deleteFBImg} className="delete-img"/>
                                    </React.Fragment>
                                }
                            </div>
                        </Upload>
                    </Form.Item>
                    <Form.Item {...tailLayout}>
                        <span>每一条留言反馈我们都会认真处理，感谢您对本站的支持。</span>
                    </Form.Item>
                    <Form.Item {...tailLayout}>
                        <Button type="primary" htmlType="submit" loading={feedbackLoading}>
                        提交反馈
                        </Button>
                    </Form.Item>
                </Form>
            </Drawer>
        </ThemeProvider>
    )
}

const mapState = (state) => ({
    userInfo: state.userInfo,
    detailTopDis: state.detailTopDis,
    detailObj: state.detailObj
})

const mapDispatch = (dispatch) => ({
    changeUserInfo(data){
		dispatch(changeUserInfo(data))
    },
    changeKeyword(data){
        dispatch(changeKeyword(data))
    },
    changeHomeTopDis(data){
        dispatch(changeHomeTopDis(data))
    }
})

export default connect(mapState, mapDispatch)(Article)